package com.jtpay.unionpay.product.utils;

import android.text.TextUtils;

public class GenerationLetter {
    private static final String CHS_STR = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

    public static String generation(String seed) {
        if (seed == null) {
            return "";
        }
        String str = numToStr(strToNum(seed) + 1);
        return formatStr(str);
    }

    public static long strToNum(String str) {
        if (TextUtils.isEmpty(str)) {
            return 0;
        }
        int len = CHS_STR.length();
        char[] chs = CHS_STR.toCharArray();
        StringBuilder sb = new StringBuilder(str.trim());
        char[] strs = sb.reverse().toString().toCharArray();
        long num = 0;
        for (int i = 0; i < strs.length; i++) {
            int ind = 0;
            for (char c : chs) {
                if (strs[i] == c) {
                    break;
                }
                ind++;
            }
            num += ind * (int) Math.pow(len, i);
        }
        return num;
    }

    public static String numToStr(long _int) {
        if (_int < 0) {
            return null;
        }
        int len = CHS_STR.length();
        char[] chs = CHS_STR.toCharArray();
        int n;
        long intVal = _int;
        StringBuffer val = new StringBuffer();
        do {
            if (intVal < len) {
                n = (int) intVal;
            } else {
                n = (int) (intVal % len);
            }
            intVal = (int) Math.floor(intVal / len);
            val.append(chs[n]);
        } while (intVal > 0);
        val = val.reverse();
        return val.toString();
    }

    public static String formatStr(String str) {
        if (TextUtils.isEmpty(str)) {
            return null;
        }
        if (str.contains(".")) {
            str = str.replace(".", "");
        }
        switch (str.length()) {
            case 1:
                str = String.format("AAA%1s", str);
                break;
            case 2:
                str = String.format("AA%1s", str);
                break;
            case 3:
                str = String.format("A%1s", str);
                break;
            case 4:
                str = String.format("%1s", str);
                break;
        }
        return str;
    }
}
